<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>文档标题</title>
  <!-- 不允许缩放 -->
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
  <!-- 优先选择chrome 内核 -->
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <link rel="stylesheet " type="text/css " href="css/globle.css " />
  <link rel="stylesheet " type="text/css " href="css/style.css " />
  <style type="text/css">
  body {
    font-size: 20px;
  }
  </style>
  <script src='js/jquery.js'></script>
</head>

<body>
  <span>发起get请求</span>
  <!-- get请求 响应的内容 -->
  <div class="get-box"></div>
  <div class="post-button">发起post请求</div>
  <!-- post请求 响应的内容 -->
  <div class="post-box"></div>

  <div class="json-button">获取json文件</div>
  <!-- get请求 响应的内容 -->
  <div class="json-box"></div>
</body>

</html>
<script type="text/javascript">
// 发起一个get请求
$('span').on('click', function(ev) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        alert(xhr.responseText);
        $('.get-box').html(xhr.responseText);
      }
    }
  }
  var ran = Math.floor(Math.random() * 100);
  xhr.open('GET', '/ajaxget?name=name&age=' + ran, true);
  xhr.send(null);
})

// 发起一个post请求
$('.post-button').on('click', function(ev) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        alert(xhr.responseText);
        $('.post-box').html(xhr.responseText);
      }
    }
  }
  var ran = Math.floor(Math.random() * 100);
  xhr.open('POST', '/ajaxpost', true);

  // get 请求在？后面传参
  // post 请求在send()里传参
  // 当是post请求时，需要告诉服务器是post (通过设置请求头)
  // 请求头一定要设置在xhr.open()方法之后 xhr.send() 之前
  // 用户ajax 模拟一个form表单请求
  xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  xhr.send('name=name&age=' + ran);

});
// 请求json数据
$('.json-button').on('click',function(){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        alert(xhr.responseText);
        $('.json-box').html(xhr.responseText);
      }
    }
  }
  xhr.open('GET','/students.json',true);
  xhr.send(null);
});

</script>
